﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Data;
using UI.Common;
using System.Windows.Forms;
using System.Collections;
using Components;
using Com.Seezt.Skins;

namespace UI.Lib.Factory
{
    public class CommonHelper
    {
        //是否登录
        bool isLogin = false;

        public static bool serverOut = false;

        private static CommonHelper _entity;

        public static CommonHelper Entity
        {
            get
            {
                if (null == _entity)
                {
                    _entity = new CommonHelper();
                }
                return _entity;
            }
        }

        private Common.CommonContractClient GetServiceEntity()
        {
            try
            {
                return new CommonContractClient();
            }
            catch
            {
                CommonHelper.serverOut = true;
            }

            return null;
        }

        /// <summary>
        /// 登出
        /// </summary>
        public void LoginOut()
        {
            MessageBox.Show("登录超时或者您已在其它地方登录，请重新登录！", "错误");
            Context.AddCache("exit", "auto");
            Application.Exit();
        }

        #region 与服务的接入点

        /// <summary>
        /// 根据页面和控件名称得到页面字段信息
        /// </summary>
        /// <param name="page">页面名称</param>
        /// <param name="ctl">控件名称</param>
        /// <returns></returns>
        public DataTable GetColumnByPageAndCtl(string page, string ctl)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                SecurityEncryption.key = Context.PrivateKey;
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    try
                    {
                        DataTable dt = c.GetColumnByPageAndCtl(SecurityEncryption.Encrypt(page),
                                                               SecurityEncryption.Encrypt(ctl), Context.LoginKey,
                                                               ref isLogin);
                        if (!isLogin) LoginOut();
                        return dt;
                    }
                    catch (SystemException ex)
                    {
                        MessageBox.Show(ex.Message, "提示");
                    }
                }
            }
            return null;
        }

        public Dictionary<string, DataTable> GetColumnByPageAndCtls(string page, string[] ctls)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                SecurityEncryption.key = Context.PrivateKey;
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    try
                    {
                        string enCtl = SecurityEncryption.Encrypt(Json.ToString(ctls));

                        string stream = c.GetColumnByPageAndCtls(SecurityEncryption.Encrypt(page), enCtl,
                                                                 Context.LoginKey, ref isLogin);
                        if (!isLogin) LoginOut();

                        stream = StringUtil.UnZip(stream);
                        var ret = Json.ToObject<Dictionary<string, string>>(stream);
                        var dict = new Dictionary<string, DataTable>();
                        foreach (var kv in ret)
                            dict.Add(kv.Key, Json.ToObject<DataTable>(kv.Value));

                        return dict;
                    }
                    catch (SystemException ex)
                    {
                        MessageBox.Show(ex.Message, "提示");
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 得到Main页面分页数据
        /// </summary>
        /// <param name="pager"></param>
        /// <returns></returns>
        public Model.ReturnPageData GetPageList(Pager pager)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    try
                    {
                        ReturnPageData rd = c.GetPageList(pager, Context.LoginKey, ref isLogin);
                        if (!isLogin) LoginOut();
                        Model.ReturnPageData model = new Model.ReturnPageData(rd.AllRowCount);

                        model.ParseData(rd.Data);

                        model.ParseSummary(rd.Summary);

                        return model;
                    }
                    catch (SystemException ex)
                    {
                        MessageBox.Show(ex.Message, "提示");
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 根据页面和控件得到页面控件实体
        /// </summary>
        /// <param name="page"></param>
        /// <param name="ctl"></param>
        /// <returns></returns>
        public String GetSys5a00(string page, string ctl)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    SecurityEncryption.key = Context.PrivateKey;
                    try
                    {
                        String model = c.GetSys5a00(SecurityEncryption.Encrypt(page), SecurityEncryption.Encrypt(ctl),
                                                    Context.LoginKey, ref isLogin);
                        if (!isLogin) LoginOut();
                        return StringUtil.UnZip(model);
                    }
                    catch (SystemException ex)
                    {
                        MessageBox.Show(ex.Message, "提示");
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 公用的保存方法
        /// </summary>
        /// <param name="callFun">保存时候调用的业务逻辑层的方法</param>
        /// <param name="data">Json字符串</param>
        /// <returns></returns>
        public String Save(string callFun, string data, string action)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    SecurityEncryption.key = Context.PrivateKey;
                    try
                    {
                        String model = c.Save(SecurityEncryption.Encrypt(callFun),
                                              SecurityEncryption.Encrypt(data), SecurityEncryption.Encrypt(action),
                                              Context.LoginKey, ref isLogin);
                        if (!isLogin) LoginOut();
                        return model;
                    }
                    catch (SystemException ex)
                    {
                        return ex.Message;
                    }
                }
            }

            //return null;
        }

        public DataTable[] GetTables(string callFun, string where)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    SecurityEncryption.key = Context.PrivateKey;
                    try
                    {
                        DataTable[] tbs = c.GetTables(SecurityEncryption.Encrypt(callFun),
                                                      SecurityEncryption.Encrypt(where), Context.LoginKey, ref isLogin);
                        if (!isLogin) LoginOut();
                        return tbs;
                    }
                    catch (SystemException ex)
                    {
                        LogHelper.Entity.Out(ex.ToString());
                        return null;
                    }
                }
            }
        }

        /// <summary>
        /// 公用的保存方法
        /// </summary>
        /// <param name="callFun">保存时候调用的业务逻辑层的方法</param>
        /// <param name="data">概要Json字符串</param>
        /// <returns></returns>
        public String SaveDtl(string callFun, string data, string action, DataTable dtldata, DataTable deldata)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    SecurityEncryption.key = Context.PrivateKey;
                    try
                    {
                        String model = c.SaveDtl(SecurityEncryption.Encrypt(callFun),
                                                 SecurityEncryption.Encrypt(data), SecurityEncryption.Encrypt(action),
                                                 dtldata, deldata, Context.LoginKey, ref isLogin);
                        if (!isLogin) LoginOut();
                        return model;
                    }
                    catch (Exception ex)
                    {
                        return ex.Message;
                    }
                }
            }

            //return null;
        }

        /// <summary>
        /// 加载修改数据
        /// </summary>
        /// <param name="page"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public DataTable LoadEditData(string page, string action, string ctl, string where)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    try
                    {
                        SecurityEncryption.key = Context.PrivateKey;
                        DataTable model = c.LoadEditData(SecurityEncryption.Encrypt(page),
                                                         SecurityEncryption.Encrypt(action),
                                                         SecurityEncryption.Encrypt(ctl),
                                                         SecurityEncryption.Encrypt(where), Context.LoginKey,
                                                         ref isLogin);
                        if (!isLogin) LoginOut();
                        return model;
                    }
                    catch (SystemException ex)
                    {

                        MessageBox.Show(ex.Message, "提示");
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 得到PopWin的数据
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public DataTable GetPopData(string tableName, string fields, string otherFieldName, string order, string where, string otherWhere, int rownum)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    SecurityEncryption.key = Context.PrivateKey;
                    try
                    {
                        string stream = c.GetPopData(SecurityEncryption.Encrypt(tableName),
                                                     SecurityEncryption.Encrypt(fields),
                                                     SecurityEncryption.Encrypt(otherFieldName),
                                                     SecurityEncryption.Encrypt(order),
                                                     SecurityEncryption.Encrypt(where),
                                                     SecurityEncryption.Encrypt(otherWhere), rownum, Context.LoginKey,
                                                     ref isLogin);
                        if (!isLogin) LoginOut();

                        return Json.ToTableUnZip(stream);
                    }
                    catch (SystemException ex)
                    {

                        MessageBox.Show(ex.Message, "提示");
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 交换MAC
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public string Exchange(string key)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();

                    string refsult = c.Exchange(key);
                    if (null == refsult || refsult.StartsWith("E1"))
                    {
                        throw new PsException(900, (null == refsult) ? "未知错误!" : refsult.Replace("E1|", ""));
                    }

                    return refsult;
                }
            }
        }

        public DataTable ExecFun(string key, Hashtable where)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    string str = Components.StringUtil.Entity.TableToJson(where);
                    try
                    {
                        string stream = c.ExecFun(key, str, Context.LoginKey, ref isLogin);
                        if (!isLogin) LoginOut();

                        string xml = StringUtil.UnZip(stream);
                        return Json.XmlToTable(xml);
                    }
                    catch (SystemException ex)
                    {

                        MessageBox.Show(ex.Message, "提示");
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 返回首行首列
        /// </summary>
        /// <param name="key"></param>
        /// <param name="where"></param>
        /// <returns></returns>
        public string ExecFunScalar(string key, Hashtable where)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    string str = Components.StringUtil.Entity.TableToJson(where);
                    string rstr = c.ExecFunScalar(key, str, Context.LoginKey, ref isLogin);
                    if (!isLogin)
                    {
                        LoginOut();
                        return null;
                    }

                    return rstr;
                }
            }
        }

        public DataTable GetSessionList(Pager page)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    DataTable data = c.GetSession(page, Context.LoginKey, ref isLogin);
                    if (!isLogin)
                    {
                        LoginOut();
                        return null;
                    }

                    return data;
                }
            }
        }

        public DataTable ExecFun(string key, params KeyValuePair<string, object>[] ps)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    string str = Components.StringUtil.Entity.KvToJSON(ps);
                    try
                    {
                        string stream = c.ExecFun(key, str, Context.LoginKey, ref isLogin);
                        if (!isLogin) LoginOut();

                        string xml = StringUtil.UnZip(stream);
                        return Json.XmlToTable(xml);
                    }
                    catch (SystemException ex)
                    {

                        MessageBox.Show(ex.Message, "提示");
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 得到PopItem对象
        /// </summary>
        /// <param name="popno"></param>
        /// <returns></returns>
        public PopItem GetPopItem(string popno)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    SecurityEncryption.key = Context.PrivateKey;
                    try
                    {
                        PopItem model = c.GetPopItem(SecurityEncryption.Encrypt(popno), Context.LoginKey, ref isLogin);
                        if (!isLogin) LoginOut();
                        return model;
                    }
                    catch (SystemException ex)
                    {

                        MessageBox.Show(ex.Message, "提示");
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 得到权限列表
        /// </summary>
        /// <returns></returns>
        public DataTable GetCurrentPermision()
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    try
                    {
                        string stream = c.GetPermision(Context.LoginKey, ref isLogin);
                        if (!isLogin) LoginOut();
                        return Json.ToTableUnZip(stream);
                    }
                    catch (SystemException ex)
                    {

                        MessageBox.Show(ex.Message, "提示");
                    }
                }
            }
            return null;
        }

        public bool DataInData(string tbName, Hashtable hs)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    SecurityEncryption.key = Context.PrivateKey;
                    string where = Components.StringUtil.Entity.TableToJson(hs);
                    try
                    {
                        bool model = c.DataInDb(SecurityEncryption.Encrypt(tbName),
                                                SecurityEncryption.Encrypt(where), Context.LoginKey, ref isLogin);
                        if (!isLogin) LoginOut();
                        return model;
                    }
                    catch (SystemException ex)
                    {
                        MessageBox.Show(ex.Message, "提示");
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 得到权限列表
        /// </summary>
        /// <param name="modulecode"></param>
        /// <returns></returns>
        public string GetActionList(string modulecode)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                using (OperationContextScope scope = new OperationContextScope(c.InnerChannel))
                {
                    CreateSoapHeader();
                    try
                    {
                        string model = c.GetActionList(modulecode, Context.LoginKey, ref isLogin);
                        if (!isLogin) LoginOut();
                        return model;
                    }
                    catch (SystemException ex)
                    {

                        MessageBox.Show(ex.Message, "提示");
                    }
                }
            }

            return null;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        /// <returns>代码|返回消息</returns>
        public string Login(String userName, String pwd, string stkcode, bool mk)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                try
                {
                    return c.Login(userName, pwd, stkcode, mk);
                }
                catch (SystemException ex)
                {

                    MessageBox.Show(ex.Message, "提示");
                }
            }

            return "";
        }

        /// <summary>
        /// 等到版本列表
        /// </summary>
        /// <returns></returns>
        public string GetVesionList()
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                return (CommonHelper.serverOut) ? "" : c.GetVesionList();
            }
        }

        public string LoginOut(string guid)
        {
            using (CommonContractClient c = GetServiceEntity())
            {
                if (Context.IsLoginOut || CommonHelper.serverOut) return ""; //本地已经登出了
                try
                {
                    return c.LoginOut(guid);
                }
                catch (SystemException ex)
                {
                    MessageBox.Show(ex.Message, "提示");
                }
            }

            return "";
        }

        #endregion

        private void CreateSoapHeader()
        {
            MessageHeader<string> mh = new MessageHeader<string>(Context.LoginKey);
            MessageHeader header = mh.GetUntypedHeader("AuthKey", Globals.ProductUrl);//设置名称和命名空间
            OperationContext.Current.OutgoingMessageHeaders.Add(header);
        }

        #region 便民的重载



        #endregion
    }
}
